/**
 * 封装axios
 * 设置请求拦截器
 * 设置响应拦截器
 * 设置统一的错误处理
 * 设置通用请求方法
 * */

import Vue from 'vue'
import axios from 'axios'
import router from '@/router' // 只有文件名为index时可以省略

/* 设置axios的请求前缀 */
axios.defaults.baseURL = process.env.VUE_APP_URL
/* 设置请求超时时间 */
axios.defaults.timeout = 1000 * 10
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8'

/* 配置请求拦截器，自动填入token到header */
axios.interceptors.request.use(request => {
  /* 从cookie中获取token */
  const token = Vue.$cookies.get('token')
  const apiToken = Vue.$cookies.get('api-token')
  if (token) {
    request.headers.token = token
  }
  if (apiToken) {
    request.headers.apiToken = apiToken
  }
  return request
})

/* 配置响应拦截器，处理code值不为200时的情况 */
axios.interceptors.response.use(response => {
  if (response.status === 200) {
    const json = response.data// 获取服务端返回的json
    if (json.code === 200) {
      return Promise.resolve(json?.data)
    } else if (json.code === 401) {
      const url = response.config.url
      if (url.includes('api')) {
        return Promise.reject(json)
      } else {
        Vue.prototype.$alert(`${json.msg},请重新登录！`, { type: 'error' }).then(() => {
          router.replace('/admin/login').then().catch(() => {})
        })
      }
    } else {
      Vue.prototype.$alert(json.msg, { type: 'error' })
      return Promise.reject(json)
    }
  } else {
    Vue.prototype.$alert(response.statusText, { type: 'error' }).then(() => {
      return Promise.reject(response)
    })
  }
})

const http = {
  get (url, params) {
    return new Promise((resolve, reject) => {
      axios.get(url, { params }).then(data => {
        resolve(data)
      }).catch(e => {
        reject(e)
      })
    })
  },
  post (url, params) {
    return new Promise((resolve, reject) => {
      axios.post(url, params).then(data => {
        resolve(data)
      }).catch(e => {
        reject(e)
      })
    })
  },
  delete (url, params) {
    return new Promise((resolve, reject) => {
      axios.delete(url, { params }).then(data => {
        resolve(data)
      }).catch(e => {
        reject(e)
      })
    })
  }
}

Vue.prototype.$http = http
Vue.prototype.$axios = axios
